<template>
  <div class="vacation-container">
    <div class="vacation-container-inner">
      <h1 class="vacation-title">{{ currentYear }}年法定节假日安排</h1>

      <div class="year-selector">
        <a-button type="primary" @click="changeYear(-1)">上一年</a-button>
        <span class="year-display">{{ currentYear }}</span>
        <a-button type="primary" @click="changeYear(1)">下一年</a-button>
      </div>

      <a-spin :spinning="vacationStore.isLoading">
        <template v-if="vacationStore.error">
          <a-alert type="error" :message="vacationStore.error" show-icon />
        </template>

        <template v-else>
          <div class="holiday-summary">
            <div class="legend">
              <span class="legend-item holiday"> <span class="dot"></span>放假日（{{ getHolidayCount() }}天） </span>
              <span class="legend-item workday"> <span class="dot"></span>补班日（{{ getWorkdayCount() }}天） </span>
              <span class="legend-item weekend"> <span class="dot"></span>周末 </span>
              <span class="legend-item festival"> <span class="dot"></span>其他节日 </span>
            </div>
          </div>

          <div class="calendar-container">
            <div v-for="month in 12" :key="month" class="month-calendar">
              <h3 class="month-title">{{ month }}月</h3>
              <div class="weekday-header">
                <span v-for="day in weekDays" :key="day" :class="{ 'weekend-header': day === '日' || day === '六' }">
                  {{ day }}
                </span>
              </div>
              <div class="days-grid">
                <div v-for="empty in getMonthStartDay(month)" :key="'empty-' + empty" class="day empty"></div>
                <div v-for="day in getMonthDays(month)" :key="day" :class="getDayClass(month, day)" @mouseenter="handleMouseEnter($event, month, day)" @mousemove="updateTooltipPosition" @mouseleave="hideTooltip">
                  <div class="day-content">
                    <span class="day-number">{{ day }}</span>
                    <div v-if="getHolidayName(month, day)" class="holiday-name">{{ getHolidayName(month, day) }}</div>
                  </div>
                  <div v-if="isHoliday(month, day)" class="holiday-marker">休</div>
                  <div v-if="isWorkday(month, day)" class="workday-marker">班</div>
                </div>
              </div>
            </div>
          </div>

          <a-tooltip :visible="tooltipVisible" :title="tooltipContent" :mouseEnterDelay="0.1" :mouseLeaveDelay="0.1" :overlayStyle="{ pointerEvents: 'none' }">
            <template #title>
              <div style="white-space: pre-line">{{ tooltipContent }}</div>
            </template>
            <div class="tooltip-trigger" :style="tooltipStyle"></div>
          </a-tooltip>
        </template>
      </a-spin>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useVacationStore } from '@/stores/vacation'

const currentYear = ref(new Date().getFullYear())
const vacationStore = useVacationStore()
const tooltipVisible = ref(false)
const tooltipContent = ref('')
const tooltipTrigger = ref(null)

const weekDays = ['日', '一', '二', '三', '四', '五', '六']

// 获取某月的天数
const getMonthDays = (month) => {
  return new Date(currentYear.value, month, 0).getDate()
}

// 获取某月1号是星期几
const getMonthStartDay = (month) => {
  return new Date(currentYear.value, month - 1, 1).getDay()
}

// 格式化日期为 YYYY-MM-DD
const formatDate = (month, day) => {
  const monthStr = String(month).padStart(2, '0')
  const dayStr = String(day).padStart(2, '0')
  return `${currentYear.value}-${monthStr}-${dayStr}`
}

// 判断是否是节假日
const isHoliday = (month, day) => {
  const date = formatDate(month, day)
  const dayInfo = vacationStore.holidayData[date]
  return dayInfo?.holiday === true
}

// 判断是否是调休工作日
const isWorkday = (month, day) => {
  const date = formatDate(month, day)
  const dayInfo = vacationStore.holidayData[date]
  return dayInfo?.holiday === false
}

// 获取日期单元格的样式类
const getDayClass = (month, day) => {
  const classes = ['day']
  const date = formatDate(month, day)
  const dayInfo = vacationStore.holidayData[date]
  const otherHoliday = vacationStore.otherHolidays[date]

  // 添加周末样式
  const dayOfWeek = new Date(date).getDay()
  if (dayOfWeek === 0 || dayOfWeek === 6) {
    classes.push('weekend')
  }

  // 添加节假日样式
  if (dayInfo?.holiday === true) {
    classes.push('holiday')
    if (dayOfWeek === 0 || dayOfWeek === 6) {
      classes.push('holiday-weekend')
    }
  }

  // 添加调休工作日样式
  if (dayInfo?.holiday === false) {
    classes.push('workday')
  }

  // 添加其他节日样式
  if (otherHoliday) {
    classes.push('festival')
  }

  return classes
}

// 获取节假日天数
const getHolidayCount = () => {
  return Object.values(vacationStore.holidayData).filter((info) => info.holiday === true).length
}

// 获取补班天数
const getWorkdayCount = () => {
  return Object.values(vacationStore.holidayData).filter((info) => info.holiday === false).length
}

// 计算距离下一个节假日的天数
const calculateDaysToNextHoliday = (currentDate) => {
  const current = new Date(currentDate)
  const holidayDates = Object.keys(vacationStore.holidayData)
    .filter((date) => vacationStore.holidayData[date].holiday === true)
    .map((date) => new Date(date))
    .filter((date) => date > current)
    .sort((a, b) => a - b)

  if (holidayDates.length === 0) {
    return null // 没有找到下一个节假日
  }

  const nextHoliday = holidayDates[0]
  const diffTime = nextHoliday.getTime() - current.getTime()
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
  return diffDays
}

// 添加 tooltip 位置相关的响应式变量
const tooltipStyle = ref({
  position: 'fixed',
  left: '0px',
  top: '0px'
})

// 处理鼠标进入事件
const handleMouseEnter = (event, month, day) => {
  updateTooltipPosition(event)
  showTooltip(month, day)
}

// 更新 tooltip 位置
const updateTooltipPosition = (event) => {
  if (tooltipVisible.value) {
    tooltipStyle.value = {
      position: 'fixed',
      left: `${event.clientX + 15}px`,
      top: `${event.clientY + 15}px`
    }
  }
}

// 修改 showTooltip 函数
const showTooltip = (month, day) => {
  const date = formatDate(month, day)
  const dayInfo = vacationStore.holidayData[date]
  const otherHoliday = vacationStore.otherHolidays[date]

  if (dayInfo) {
    let tipContent = []
    tipContent.push(dayInfo.name)

    if (dayInfo.holiday) {
      tipContent.push('放假')
    } else {
      tipContent.push('补班')
    }

    if (dayInfo.wage > 1) {
      tipContent.push(`${dayInfo.wage}倍工资`)
    }

    if (dayInfo.target && !dayInfo.holiday) {
      tipContent.push(`${dayInfo.target}${dayInfo.after ? '后' : '前'}补班`)
    }

    // 使用动态计算的距离下一个节假日天数
    if (!dayInfo.holiday) {
      const daysToNext = calculateDaysToNextHoliday(date)
      if (daysToNext !== null) {
        tipContent.push(`距离下一个节假日还有${daysToNext}天`)
      }
    }

    tooltipContent.value = tipContent.join('\n')
    tooltipVisible.value = true
  } else if (otherHoliday) {
    tooltipContent.value = otherHoliday.name
    tooltipVisible.value = true
  } else {
    const dayOfWeek = new Date(date).getDay()
    if (dayOfWeek === 0 || dayOfWeek === 6) {
      tooltipContent.value = '周末'
      tooltipVisible.value = true
    } else {
      // 对于普通工作日，也显示距离下一个节假日的天数
      const daysToNext = calculateDaysToNextHoliday(date)
      if (daysToNext !== null) {
        tooltipContent.value = `距离下一个节假日还有${daysToNext}天`
        tooltipVisible.value = true
      }
    }
  }
}

// 修改隐藏 tooltip 的函数
const hideTooltip = () => {
  tooltipVisible.value = false
}

// 切换年份
const changeYear = (delta) => {
  currentYear.value += delta
  vacationStore.fetchHolidayData(currentYear.value)
}

// 组件挂载时获取数据
onMounted(() => {
  vacationStore.fetchHolidayData(currentYear.value)
})

// 获取节日名称
const getHolidayName = (month, day) => {
  const date = formatDate(month, day)
  // 优先显示法定节假日
  const dayInfo = vacationStore.holidayData[date]
  if (dayInfo?.name) {
    return dayInfo.name
  }
  // 其次显示其他节日
  const otherHoliday = vacationStore.otherHolidays[date]
  return otherHoliday?.name
}
</script>

<style scoped>
.vacation-container-inner {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}
.vacation-container {
  overflow-y: scroll;
  width: 100%;
  height: 100%;
  padding-bottom: 100px;
}

.vacation-title {
  text-align: center;
  color: #344767;
  margin-bottom: 30px;
}

.year-selector {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 30px;
  gap: 20px;
}

.year-display {
  font-size: 20px;
  font-weight: bold;
  min-width: 80px;
  text-align: center;
}

.calendar-container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.month-calendar {
  border: 1px solid #f0f0f0;
  border-radius: 4px;
  padding: 10px;
}

.month-title {
  text-align: center;
  margin-bottom: 10px;
  color: #344767;
}

.weekday-header {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  text-align: center;
  font-weight: bold;
  margin-bottom: 5px;
}

.weekday-header span {
  padding: 5px;
  color: #666;
}

.days-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 2px;
}

.day {
  position: relative;
  aspect-ratio: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid #f0f0f0;
  cursor: pointer;
  font-size: 14px;
  padding: 2px;
}

.day:hover {
  background-color: #f5f5f5;
}

.empty {
  background-color: #fafafa;
}

.weekend {
  color: #ff4d4f;
}

.weekend.workday {
  color: #fa8c16 !important;
}

.holiday {
  background-color: #f6ffed !important;
  border-color: #b7eb8f !important;
  color: #52c41a !important;
}

.holiday-weekend {
  color: #389e0d !important; /* 深绿色，区分普通节假日 */
}

.workday {
  background-color: #fff7e6 !important;
  border-color: #ffd591 !important;
  color: #fa8c16 !important;
}

.holiday-marker,
.workday-marker {
  position: absolute;
  top: 0;
  right: 0;
  font-size: 10px;
  line-height: 1;
  padding: 2px 4px;
  border-radius: 0 2px 0 4px;
  font-weight: bold;
  z-index: 1;
}

.holiday-marker {
  background-color: #52c41a;
  color: #fff;
}

.workday-marker {
  background-color: #fa8c16;
  color: #fff;
}

.tooltip-trigger {
  position: fixed;
  width: 1px;
  height: 1px;
  pointer-events: none;
  opacity: 0;
  z-index: -1;
}

/* 修改 tooltip 样式 */
:deep(.ant-tooltip) {
  max-width: 300px;
  pointer-events: none;
}

:deep(.ant-tooltip-inner) {
  white-space: pre-line;
  padding: 8px 12px;
}

@media (max-width: 1200px) {
  .calendar-container {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .calendar-container {
    grid-template-columns: 1fr;
  }
}

.holiday-summary {
  margin-bottom: 20px;
  padding: 15px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.legend {
  display: flex;
  justify-content: center;
  gap: 20px;
  flex-wrap: wrap; /* 允许在小屏幕上换行 */
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 5px;
}

.dot {
  width: 10px;
  height: 10px;
  border-radius: 50%;
}

.legend-item.holiday .dot {
  background-color: #52c41a;
}

.legend-item.workday .dot {
  background-color: #fa8c16;
}

.legend-item.weekend .dot {
  background-color: #ff4d4f;
}

.weekend-header {
  color: #ff4d4f !important;
}

.day-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  gap: 2px;
}

.day-number {
  font-size: 14px;
}

.holiday-name {
  font-size: 10px;
  line-height: 1.2;
  text-align: center;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  word-break: break-all;
}

.holiday .holiday-name {
  color: #389e0d;
}

.workday .holiday-name {
  color: #d46b08;
}

@media (max-width: 768px) {
  .day {
    font-size: 12px;
  }

  .holiday-name {
    font-size: 9px;
  }
}

.festival {
  background-color: #f9f0ff !important; /* 浅紫色背景 */
  border-color: #d3adf7 !important;
}

.festival .holiday-name {
  color: #722ed1; /* 深紫色文字 */
  font-size: 9px;
}

/* 当节日与法定节假日或调休日重叠时，保持原有样式 */
.holiday.festival {
  background-color: #f6ffed !important;
  border-color: #b7eb8f !important;
}

.workday.festival {
  background-color: #fff7e6 !important;
  border-color: #ffd591 !important;
}

.legend-item.festival .dot {
  background-color: #722ed1;
}
</style>
